package com.abocode.smarten.client.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import io.netty.channel.ChannelHandler.Sharable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Define a  {@code NettyClientHandler} implementations {@link SimpleChannelInboundHandler}.
 *
 * @author: guanxianfei
 * @date: 2019/7/24
 */
@Sharable
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
    private final LinkedBlockingQueue<String> queue;

    public NettyClientHandler() {
        queue = new LinkedBlockingQueue<String>();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) {
        queue.add(message);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.info("Unexpected exception from downstream.", cause);
        ctx.close();
    }

    public String getMessage() {
        String message = null;
        try {
            message = queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     *
     * @param timeout 超时时间，单位秒
     * @return
     */
    public String getMessage(long timeout) {
        String message = null;
        try {
            message = queue.poll(timeout, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return message;
    }
}
